package com.oocl.service.impl;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.oocl.activemq.JMSProducer;
import com.oocl.dao.MerchantsDao;
import com.oocl.dao.base.BaseDao;
import com.oocl.dto.MerchantDTO;
import com.oocl.entity.Merchants;
import com.oocl.security.SHASecurity;
import com.oocl.security.SecretKeys;
import com.oocl.service.MerchantsService;
import com.oocl.util.FileOperatorUtil;
import com.oocl.util.RequestUtil;
import com.oocl.util.VoUtil;
import com.oocl.vo.MerchantsVo;


@Service("merchantsService")
public class MerchantsServiceImpl implements MerchantsService{
     
	@Autowired
	private MerchantsDao merchantsDao; 
	@Autowired
	private BaseDao baseDao; 
	@Autowired
	JMSProducer jmsproducer;
	
	
	@Value("#{configProperties['icpicFilePath']}")
	private String 	icpicFilePath;
	@Value("#{configProperties['porFilePath']}")
	private String porFilePath;
	@Value("#{configProperties['icpicUrlPath']}")
	private String icpicUrlPath;
	@Value("#{configProperties['porUrlPath']}")
	private String porUrlPath;
	
	
	/*
	 * @Method: addMerchant
	 * @function: add a Merchant for register
	 * @param param register parameters Map (include picture file .etc)
	 * @author garen
	 * @date 2017-08-12
	 */
	@Transactional
	public void addMerchant(Map<String,Object> param) throws IllegalStateException, IOException {
		MultipartFile icpicFile = (MultipartFile) param.get("icpicFile");
		MultipartFile portraitFile = (MultipartFile) param.get("portraitFile"); 
		Merchants m = (Merchants) param.get("merchant");
		if(!icpicFile.isEmpty()){
			String icpicName = FileOperatorUtil.getFileName()+icpicFile.getOriginalFilename();//前面加上随机串，避免文件名重复
			String icpicFilePosition = icpicFilePath+icpicName;
			FileOperatorUtil.saveFile(icpicFile, icpicFilePosition);
			String icpicUrl = icpicUrlPath+icpicName;
			m.setIcpic(icpicUrl);
		}
		if(!portraitFile.isEmpty()){
			String portraitName = FileOperatorUtil.getFileName()+portraitFile.getOriginalFilename();//前面加上随机串，避免文件名重复
			String portraitPosition = porFilePath+portraitName;
			FileOperatorUtil.saveFile(portraitFile, portraitPosition);
			String protraitUrl = porUrlPath + portraitName;
			m.setPortrait(protraitUrl);
		}
		String token = UUID.randomUUID().toString();
	    m.setToken(token);
	    m.setStatus1("1");
		baseDao.persist(m);
		MerchantDTO merchantdto = new MerchantDTO();
		merchantdto = entity2dto(m,merchantdto);
		merchantdto.setToken(token);
		String msg = RequestUtil.wrapToJson(merchantdto);
		jmsproducer.sendMessage(msg);
	}

	/*
	 * @Method: updateMerchantForRegister
	 * @function: update a Merchant and send msg to activeMq server
	 * @param m a Merchants Entity
	 * @author garen
	 * @date 2017-08-12
	 */
	@Transactional
	public void updateMerchantForRegister(Map<String,Object> param) throws Exception {
		Merchants m = (Merchants) param.get("merchant");
		MultipartFile icpicFile = (MultipartFile) param.get("icpicFile");
		MultipartFile portraitFile = (MultipartFile) param.get("portraitFile");
		System.out.println("m.getMid():    "+m.getMid());
		Merchants merchant = (Merchants) baseDao.find(Merchants.class, m.getMid());
		if(!icpicFile.isEmpty()){
			//删除旧文件
			if(merchant.getIcpic()!=null||!"".equals(merchant.getIcpic())){
				String[] strs = merchant.getIcpic().split("/");
				String icpicFileName = strs[strs.length-1];
				String oldicpicFilePosition = icpicFilePath+icpicFileName;
				FileOperatorUtil.removeFile(oldicpicFilePosition);
			}
			String icpicName = FileOperatorUtil.getFileName()+icpicFile.getOriginalFilename();//前面加上随机串，避免文件名重复
			String icpicFilePosition = icpicFilePath+icpicName;
			FileOperatorUtil.saveFile(icpicFile, icpicFilePosition);
			String icpicUrl = icpicUrlPath+icpicName;
			m.setIcpic(icpicUrl);
		}
		if(!portraitFile.isEmpty()){
			//删除旧文件
			if(merchant.getPortrait()!=null||!"".equals(merchant.getPortrait())){
				String[] strs = merchant.getPortrait().split("/");
				String porFileName = strs[strs.length-1];
				String oldporFilePosition = porFilePath+porFileName;
				FileOperatorUtil.removeFile(oldporFilePosition);
			}
			String portraitName = FileOperatorUtil.getFileName()+portraitFile.getOriginalFilename();//前面加上随机串，避免文件名重复
			String portraitPosition = porFilePath+portraitName;
			FileOperatorUtil.saveFile(portraitFile, portraitPosition);
			String protraitUrl = porUrlPath + portraitName;
			m.setPortrait(protraitUrl);
		}
		merchant = (Merchants) VoUtil.copyWithoutNull(m, merchant);
		baseDao.update(merchant);
		MerchantDTO merchantdto = new MerchantDTO();
		merchantdto = entity2dto(merchant,merchantdto);
		String msg = RequestUtil.wrapToJson(merchantdto);
		jmsproducer.sendMessage(msg);
	}
	
	
	/*
	 * @Method: updateMerchantFromA
	 * @function: update a Merchant from A system
	 * @param m a Merchants Entity
	 * @author garen
	 * @date 2017-08-12
	 */
	@Transactional
	public int updateMerchantFromA(Merchants m) throws Exception {
		System.out.println(m.getIcnum());
		System.out.println(m.getToken());
		System.out.println(m.getStatus1());
		
		Merchants merchant = merchantsDao.findmerchantsByIcnum(m.getIcnum());
		System.out.println("my:"+merchant.getToken());
		String token  =m.getToken().trim();
		if(token.equals(merchant.getToken())){
			merchant.setStatus1(m.getStatus1());
			baseDao.update(merchant);
			return 1;
		}
		return 0;
	}
	
	
	/*
	 * @Method: updateMerchant
	 * @function: update a Merchant
	 * @param m a Merchants Entity
	 * @author garen
	 * @date 2017-08-12
	 */
	@Transactional
	public void updateMerchant(Merchants m) throws Exception {
		Merchants merchant = (Merchants) baseDao.find(Merchants.class, m.getMid());
		     merchant  = (Merchants) VoUtil.copyWithoutNull(m, merchant);
			baseDao.update(merchant);
	}

	
	
	/*
	 * @Method: loginCheck
	 * @function: provide service to login 
	 * @param m a Merchants Entity
	 * @return mvo MerchantsVo
	 * @author garen
	 * @date 2017-08-12
	 */
	@Transactional
	public MerchantsVo loginCheck(Merchants m) {
		Merchants merchant = merchantsDao.loadMerchant(m);
		MerchantsVo mvo = null;
		if(merchant!=null){
			mvo = VoUtil.translate(MerchantsVo.class, merchant);
		}
		return mvo;
	}

	
	/*
	 * @Method: findByMid
	 * @function: find a Merchants by mid
	 * @param mid Merchants id
	 * * @return mvo MerchantsVo
	 * @author garen
	 * @date 2017-08-12
	 */
	public MerchantsVo findByMid(String mid) {
		Merchants merchant = (Merchants) baseDao.find(Merchants.class, mid);
		MerchantsVo mvo = null;
		if(merchant!=null){
			mvo = VoUtil.translate(MerchantsVo.class, merchant);
		}
		return mvo;
	}
	/*
	 * @Method: findByIcnum
	 * @function:  find a Merchants by icnum
	 * @param m a Merchants Entity
	 * * @return mvo MerchantsVo
	 * @author garen
	 * @date 2017-08-12
	 */
	public MerchantsVo findByIcnum(String icnum) {
		Merchants merchant = merchantsDao.findmerchantsByIcnum(icnum);
		MerchantsVo mvo = null;
		if(merchant!=null){
			mvo = VoUtil.translate(MerchantsVo.class, merchant);
		}
		return mvo;
	}
	
	/*
	 * @Method: entity2dto
	 * @function: copy Merchants entity to MerchantsDTO
	 * @param m -> a Merchants Entity,merchantdto -> MerchantDTO DTO
	 * * @return mvo MerchantsVo
	 * @author garen
	 * @date 2017-08-12
	 */
	private MerchantDTO entity2dto(Merchants m, MerchantDTO merchantdto) {
		merchantdto.setName(m.getMname());
		merchantdto.setIcNum(m.getIcnum());
		merchantdto.setAddr(m.getMaddr());
		merchantdto.setIcPicUrl(m.getIcpic());
		merchantdto.setPortraintUrl(m.getPortrait());
		return merchantdto;
	}

}
